﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Rabbit.Modal;
using Rabbit.Utils;
using Rabbit.BusinessLogicLayer;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for UCSearch.xaml
    /// </summary>
    public partial class UCSearch : UserControl
    {
        ObservableCollection<Status> StatusCollection = new ObservableCollection<Status>();
        ObservableCollection<User> UserCollection = new ObservableCollection<User>();

        #region Event
        public static readonly RoutedEvent OnSearchingStartEvent = EventManager.RegisterRoutedEvent("OnSearchingStart",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<string>), typeof(UCSearch));
        public event OneValueEventHandler<string> OnStartSearching
        {
            add { AddHandler(OnSearchingStartEvent, value); }
            remove { RemoveHandler(OnSearchingStartEvent, value); }
        }

        public static readonly RoutedEvent OnSearchingFinishedEvent = EventManager.RegisterRoutedEvent("OnSearchingFinished",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<string>), typeof(UCSearch));
        public event OneValueEventHandler<string> OnSearchingFinished
        {
            add { AddHandler(OnSearchingFinishedEvent, value); }
            remove { RemoveHandler(OnSearchingFinishedEvent, value); }
        }

        public static readonly RoutedEvent OnSearchingFailedEvent = EventManager.RegisterRoutedEvent("OnSearchingFailed",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<string>), typeof(UCSearch));

        public event OneValueEventHandler<string> OnSearchingFailed
        {
            add { AddHandler(OnSearchingFailedEvent, value); }
            remove { RemoveHandler(OnSearchingFailedEvent, value); }
        }

        public static readonly RoutedEvent OnUserHeadPictureMouseEnterEvent = EventManager.RegisterRoutedEvent("OnUserHeadPictureMouseEnter",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<User>), typeof(UCSearch));
        public event OneValueEventHandler<User> OnUserHeadPictureMouseEnter
        {
            add { AddHandler(OnUserHeadPictureMouseEnterEvent, value); }
            remove { RemoveHandler(OnUserHeadPictureMouseEnterEvent, value); }
        }
        public static readonly RoutedEvent OnUserHeadPictureMouseLeaveEvent = EventManager.RegisterRoutedEvent("OnUserHeadPictureMouseLeave",
          RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UCSearch));
        public event RoutedEventHandler OnUserHeadPictureMouseLeave
        {
            add { AddHandler(OnUserHeadPictureMouseLeaveEvent, value); }
            remove { RemoveHandler(OnUserHeadPictureMouseLeaveEvent, value); }
        }

        private void RaiseStartingEvent(string message)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                OneValueEventArgs<string> args = new OneValueEventArgs<string>(OnSearchingStartEvent);
                args.Value = message;
                RaiseEvent(args);
            }
            ));
        }
        private void RaiseFailedEvent(string message)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                OneValueEventArgs<string> args = new OneValueEventArgs<string>(OnSearchingFailedEvent);
                args.Value = message;
                RaiseEvent(args);
            }
            ));
        }
        private void RaiseFinishedEvent(string message)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                OneValueEventArgs<string> args = new OneValueEventArgs<string>(OnSearchingFinishedEvent);
                args.Value = message;
                RaiseEvent(args);
            }
            ));
        }
        #endregion

        public UCSearch()
        {
            InitializeComponent();
        }

        private void menuCopyStatus_Click(object sender, RoutedEventArgs e)
        {

        }

        private void OpenUserPage_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            Action fetchingAction;
            RaiseStartingEvent("正在搜索");

            string Keyword = txtSearchKeyword.Text;
            if (cmbSearchType.SelectedItem == cmItemStatus)
            {
                fetchingAction = () =>
                {
                    try
                    {
                        SearchedStatuses tempStatus = SearchBL.GetFirstPageSearchedStatus(Keyword);
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            StatusCollection.Clear();
                            //tbSearchResultCount.Text = "共" + tempStatus.CurrentTotalCount + "条结果";
                            tempStatus.StatusList.ForEach(status => StatusCollection.Add(status));
                        }));
                        SetPagerEnabled();
                    }
                    catch
                    {
                        RaiseFailedEvent("搜索失败,请重试");
                    }
                };
                lstSearchResult.ItemTemplate = (DataTemplate)this.FindResource("StatusItemTemplate");
                lstSearchResult.ItemsSource = StatusCollection;
            }
            else
            {
                fetchingAction = () =>
                {
                    try
                    {
                        List<User> tempUserList = SearchBL.GetFirstPageUser(Keyword);
                        this.Dispatcher.BeginInvoke(new Action(() =>
                       {
                           UserCollection.Clear();
                           tempUserList.ForEach(user => UserCollection.Add(user));
                       }));
                        SetPagerEnabled();
                    }
                    catch
                    {
                        RaiseFailedEvent("搜索失败,请重试");
                    }
                };
                lstSearchResult.ItemTemplate = (DataTemplate)this.FindResource("UserItemsTemplate");
                lstSearchResult.ItemsSource = UserCollection;
            }
            fetchingAction.BeginInvoke(null, null);
        }

        private void statusImage_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void ForwardStatusHandler(object sender, RoutedEventArgs e)
        {

        }

        private void ReplyStatusHandler(object sender, RoutedEventArgs e)
        {

        }

        private void UserHeadPicture_MouseLeave(object sender, MouseEventArgs e)
        {
            RoutedEventArgs args = new RoutedEventArgs(OnUserHeadPictureMouseLeaveEvent);
            RaiseEvent(args);
        }

        private void UserHeadPicture_MouseEnter(object sender, MouseEventArgs e)
        {
            ListBoxItem item = Rabbit.Utils.Common.GetListBoxItemFromChild(sender as DependencyObject);
            User currentUser=null;
            if (item.Content.GetType() == typeof(User))
            {
                currentUser = item.Content as User;
            }
            else if (item.Content.GetType() == typeof(Status))
            {
                currentUser = (item.Content as Status).User;
            }

            if (currentUser != null)
            {
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    OneValueEventArgs<User> args = new OneValueEventArgs<User>(OnUserHeadPictureMouseEnterEvent);
                    args.Source = sender;
                    args.Value = currentUser;
                    RaiseEvent(args);
                }
           ));
            }
        }

        #region Pager
        private void linkFirstPage_Click(object sender, RoutedEventArgs e)
        {
            btnSearch_Click(sender, e);
        }

        private void linkPreviousePage_Click(object sender, RoutedEventArgs e)
        {
            RaiseStartingEvent("正在搜索");
            if (cmbSearchType.SelectedItem == cmItemStatus)
            {
                Action fetchingAction = () =>
                {
                    try
                    {
                        SearchedStatuses tempStatus = SearchBL.GetPreviousePageSearchedStatus();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            StatusCollection.Clear();
                            //tbSearchResultCount.Text = "共" + tempStatus.CurrentTotalCount + "条结果";
                            tempStatus.StatusList.ForEach(status => StatusCollection.Add(status));
                        })); SetPagerEnabled();
                    }
                    catch
                    {
                        RaiseFailedEvent("搜索失败,请重试");
                    }

                };
                fetchingAction.BeginInvoke(null, null);
            }
            else
            {
                Action fetchingAction = () =>
                {
                    try
                    {
                        List<User> tempUsers = SearchBL.GetPreviousePageSearchedUser();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            UserCollection.Clear();
                            //tbSearchResultCount.Text = "共" + tempStatus.CurrentTotalCount + "条结果";
                            tempUsers.ForEach(user => UserCollection.Add(user));
                        }));
                        SetPagerEnabled();
                    }
                    catch
                    {
                        RaiseFailedEvent("搜索失败,请重试");
                    }
                };
                fetchingAction.BeginInvoke(null, null);
            }
        }

        private void SetPagerEnabled()
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                linkFirstPage.IsEnabled = SearchBL.currentPage > 1;
                linkPreviousePage.IsEnabled = SearchBL.currentPage > 1;
                linkNextPage.IsEnabled = !SearchBL.IsLastPage;
                OneValueEventArgs<string> args = new OneValueEventArgs<string>(OnSearchingFinishedEvent);
                args.Value = "获取成功";
                RaiseEvent(args);
            }
            ));
        }

        private void linkNextPage_Click(object sender, RoutedEventArgs e)
        {
            if (cmbSearchType.SelectedItem == cmItemStatus)
            {
                RaiseStartingEvent("正在搜索");
                Action fetchingAction = () =>
                {
                    try
                    {
                        SearchedStatuses tempStatus = SearchBL.GetNextPageSearchedStatus();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            StatusCollection.Clear();
                            //tbSearchResultCount.Text = "共" + tempStatus.CurrentTotalCount + "条结果";
                            tempStatus.StatusList.ForEach(status => StatusCollection.Add(status));
                        })); SetPagerEnabled();
                    }
                    catch
                    {
                        RaiseFailedEvent("搜索失败,请重试");
                    }
                };
                fetchingAction.BeginInvoke(null, null);
            }
            else
            {
                Action fetchingAction = () =>
                {
                    try
                    {
                        List<User> tempUsers = SearchBL.GetNextPageSearchedUser();
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            UserCollection.Clear();
                            //tbSearchResultCount.Text = "共" + tempStatus.CurrentTotalCount + "条结果";
                            tempUsers.ForEach(user => UserCollection.Add(user));
                        }));
                        SetPagerEnabled();
                    }
                    catch
                    {
                        RaiseFailedEvent("搜索失败,请重试");
                    }
                };
                fetchingAction.BeginInvoke(null, null);
            }
        } 
        #endregion

        private void MakeFriends_Click(object sender, RoutedEventArgs e)
        {
            RaiseStartingEvent("正在添加关注");
            long userID = long.Parse((sender as Hyperlink).CommandParameter.ToString());
            Action makeFriends = () =>
                {
                    try
                    {
                        User result = UserBL.CreateFriendship(userID);
                        RaiseFinishedEvent("关注成功");
                    }
                    catch (Exception)
                    {
                        RaiseFailedEvent("关注失败,您已经关注过此人");
                    }
                };
            makeFriends.BeginInvoke(null, null);
        }

        private void txtSearchKeyword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnSearch_Click(sender, e);
            }
        }
    }
}
